<template>
  <div class="mineinfo">
    <div class="header">
      <van-sticky>
        <van-nav-bar
          title="编辑个人信息"
          left-text="返回"
          left-arrow
          @click-left="onClickLeft"
        />
      </van-sticky>
    </div>
    <!-- 背景图片 -->
    <div class="bg"></div>
    <!-- 用户头像 -->
    <div class="userimage">
      <img :src="editFrom.userFace" alt="" class="imguser" />
    </div>
    <!-- 修改信息 -->
    <div class="editInfo">
      <van-form @submit="onSubmit" ref="edit_From">
        <!-- 用户名不能相同 -->
        <van-field
          v-model="editFrom.username"
          name="username"
          label="用户名"
          placeholder="用户名"
          left-icon="contact"
          clearable
          :rules="[{ required: true, message: '用户名不能为空！' }]"
        />
        <van-field
          v-model="editFrom.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          left-icon="closed-eye"
          clearable
          :rules="[{ required: true, message: '密码不能为空！' }]"
        />

        <van-field name="gender" label="性别" left-icon="passed">
          <template #input>
            <van-radio-group v-model="editFrom.gender" direction="horizontal">
              <van-radio name="男">男</van-radio>
              <van-radio name="女">女</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <van-field name="uploader" label="上传头像">
          <template #input>
            <van-uploader
              :after-read="afterRead"
              v-model="fileList"
              :max-count="1"
            />
          </template>
        </van-field>

        <van-field
          v-model="editFrom.nation"
          name="nation"
          label="民族"
          placeholder="民族"
          clearable
          left-icon="friends-o"
        />
        <van-cell
          title="选择单个日期"
          v-model="date"
          @click="show = true"
          icon="calendar-o"
        />
        <van-field
          v-model="editFrom.telephone"
          name="telephone"
          label="手机号"
          placeholder="手机号"
          clearable
          left-icon="phone-o"
          :rules="[
            { required: true, message: '请填写您的手机号码！' },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式错误！' },
          ]"
        />

        <van-field
          v-model="editFrom.email"
          name="email"
          label="电子邮箱"
          placeholder="电子邮箱"
          clearable
          left-icon="envelop-o"
          :rules="[
            { required: true, message: '请填写您的电子邮箱！' },
            {
              pattern:
                /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
              message: '电子邮箱格式格式错误！',
            },
          ]"
        />

        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
      <div style="height: 60px"></div>
    </div>
    <van-calendar
      v-model="show"
      @confirm="onConfirm"
      :min-date="minDate"
      :max-date="maxDate"
    />

    <!-- 保存按钮 -->
    <!-- <div class="saveBtn"></div> -->
  </div>
</template>

<script>
import { Toast } from "vant";
import { post_formData, post, get } from "../../http/axios";
import { Uploader } from "vant";
export default {
  data() {
    return {
      // 显示日历
      show: false,

      showCalendar: false,
      date: "",
      minDate: new Date(1871, 1, 1),
      maxDate: new Date(),
      fileList: [],
      editFrom: {
        username: "",
        password: "",
        telephone: "",
        gender: "",
        birth: "",
        email: "",
        nation: "",

        id: "",
        realname: "",
        status: "",
        userFace: "",
        registerTime: "",
        idCard: "",
        idcardPhotoPositive: "",
        idcardPhotoNegative: "",
        bankCard: "",
        bankCardPhoto: "",
        balance: "",
        certificationStatus: "",
        certificationTime: "",
      },
    };
  },
  methods: {
    // 返回页面
    onClickLeft() {
      this.$router.go(-1);
    },
    //上传
    afterRead(file, detail) {
      console.log(this.dataURLtoFileFun(file.content));
      //定义一个formData表单对象
      let formData = new FormData();
      // 调用base64转文件对象方法进行格式转换
      formData.append("file", this.dataURLtoFileFun(file.content, "file.jpg"));
      // 使用post_formData方法将包含文件的formData上传到文件服务器 文件服务器路径见swagger
      post_formData("http://121.199.29.84:8001/file/upload", formData).then(
        (res) => {
          console.log(res.data);
          if (res.data.status === 200) {
            //上传成功 将对应的图片路径保存到需要提交的表单对象中
            this.editFrom.userFace =
              "http://121.199.29.84:8888/" +
              res.data.data.groupName +
              "/" +
              res.data.data.id;
            // 保存已上传的文件路径
            this.fileList = [
              {
                url:
                  "http://121.199.29.84:8888/" +
                  res.data.data.groupName +
                  "/" +
                  res.data.data.id,
              },
            ];
          }
        }
      );
    },

    dataURLtoFileFun(dataurl, filename) {
      // 将base64转换为文件，dataurl为base64字符串，filename为文件名（必须带后缀名，如.jpg,.png）
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    //整合数据提交
    submitHandler() {
      this.editFrom.userId = this.$route.query.id;
      console.log(this.editFrom);
      post("/certification/submitCertificationApply", this.editFrom).then(
        (res) => {
          console.log(res.data.status);
          if (res.data.status === 200) {
            Toast(res.data.message);
            this.$router.push("/manager/mine");
          } else {
            Toast(res.data.message);
          }
        }
      );
    },
    //提交表单
    async onSubmit() {
      if (this.editFrom.username == "admin" && this.editFrom.roles.id != 2) {
        Toast.fail("用户名不能为admin！");
      } else {
        // console.log(this.editFrom);
        let res = await post("/baseUser/saveOrUpdate", this.editFrom);
        // this.submitHandler();
        //给用户一个成功的提示
        Toast.success("用户信息更新成功！");
        this.$router.push({
          path: "/manager/mine",
        });
      }
    },
    // 日期选择
    onConfirm(date) {
      this.show = false;
      this.date = this.formatDate(date);
    },
    formatDate(date) {
      console.log(this.date);
      this.editFrom.birth = `${date.getFullYear()}/${
        date.getMonth() + 1
      }/${date.getDate()}`;
      // console.log(this.editFrom.birth);
      return this.editFrom.birth;
    },
  },
  created() {
    this.editFrom = { ...this.$route.query };
    // console.log(new Date());
  },
};
</script>

<style >
.van-radio__icon--checked .van-icon {
  color: #fff;
  background-color: #ee0a24;
  border-color: #ee0a24;
}
.van-button--info {
  color: #fff;
  background: linear-gradient(45deg, rgb(255, 96, 52), rgb(238, 10, 36));
  border-color: #ee0a24;
}
.bg {
  height: 200px;
  background: #ff8917;
  border-bottom-right-radius: 50%;
  border-bottom-left-radius: 50%;
}

.userimage {
  width: 115px;
  height: 115px;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  /* background-color: blueviolet; */
  transform: translate(-50%, -50%);
  top: 130px;
}
.imguser {
  height: 100%;
  width: 100%;
  border-radius: 50%;
}
.editInfo {
  width: 90%;
  height: 500px;
  /* border: 1px solid rebeccapurple; */
  position: absolute;
  transform: translate(6%, -8%);
  box-shadow: rgb(204 204 204) 0px 0px 10px;
  opacity: 0.9;
  background-color: #fff;
}
</style>